<?php
namespace app\Admin\controller;

//引入公共控制器
use app\common\controller\Backend;

//引入数据库
use think\Db;

use think\Request;

class User extends Backend {
    //默认配置

    public function __construct() {

        // 继承父类
        parent::__construct();

        // 引入模型
        $this->ConfigModel = model( 'Config' );
        $this->UserModel = model( 'User.User' );
        $this->RegionModel = model( 'Region' );
    }

    // 用户管理界面

    public function index() {

        // 获取开始时间
        $start = $this->request->param( 'start', '' );

        // 获取结束时间
        $end = $this->request->param( 'end', '' );

        // 获取关键字
        $keywords = $this->request->param( 'keywords', '' );

        // 条件集合
        $where = [];

        if ( $start ) {
            // 加入条件 大于开始时间
            $where[ 'createtime' ] = [ '> time', $start ];
        }

        if ( $end ) {
            // 加入条件 小于或等于结束时间
            $where[ 'createtime' ] = [ '<= time', $end ];
        }

        // 若两个都存在就将两个条件拼接
        if ( $start && $end ) {
            $where[ 'createtime' ] = [ 'between time', [ $start, $end ] ];
        }

        if ( $keywords ) {
            // 加入条件 关键字
            $where[ 'nickname' ] = [ 'like', "%$keywords%" ];
        }

        // 全部用户的数量
        $userAll = $this->UserModel->select();

        $userCount = count( $userAll );

        // 获取全部用户
        $userList = $this->UserModel->where( $where )->order( 'id', 'desc' )->paginate( 10, false, [ 'query' => Request::instance()->param() ] );

        // 获取分页显示
        $userListstr = $userList->render();

        $this->assign( [
            'userList' => $userList,
            'userListstr' => $userListstr,
            'userCount' => $userCount,
            'keywords' => $keywords,
            'start' => $start,
            'end' => $end,
        ] );
        return $this->fetch();
    }

    /* 软删除用户 */

    public function del() {
        if ( $this->request->isPost() ) {
            // 提示信息
            $success = [
                'result' => false,
                'msg' => '',
            ];

            $ids = $this->request->param( 'ids', 0 );

            // 软删除
            $result = $this->UserModel->destroy( $ids );

            if ( $result === FALSE ) {
                $success[ 'result' ] = false;
                $success[ 'msg' ] = $this->UserModel->getError();
            } else {
                $success[ 'result' ] = true;
                $success[ 'msg' ] = '添加回收站成功！';
            }

            return json( $success );
        }
    }

    // 修改用户

    public function edit() {

        // 获取url传来的数据
        $userId = $this->request->param( 'id', 0 );

        // 根据id获取配置信息
        $userInfo = $this->UserModel->find( $userId );

        //查询地区表的省份数据
        $province = $this->RegionModel->where( [ 'grade' => 1 ] )->select();

        //判断当前这个用户是否有选择省份
        if ( empty( $userInfo[ 'province' ] ) ) {

            $city = [];
        } else {

            $city = $this->RegionModel->where( [ 'parentid' => $userInfo[ 'province' ] ] )->select();
        }

        //判断当前用户是否有选择城市
        if ( empty( $userInfo[ 'city' ] ) ) {
            $district = [];
        } else {
            $district = $this->RegionModel->where( [ 'parentid' => $userInfo[ 'city' ] ] )->select();
        }

        // 渲染到界面
        $this->assign( [
            'userInfo'=> $userInfo,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'userId' => $userId
        ] );

        if ( $this->request->isPost() ) {
            // 获取表单信息
            $params = $this->request->param();

            if ( empty( request()->file( 'avatar' ) ) ) {
                $avatarImgURL = isset( $params[ 'avatar' ] ) ? $params[ 'avatar' ] : '';
            } else {
                // 头像图片上传
                $avatarImgURL = upload( 'avatar' );

                if ( $avatarImgURL === false ) {
                    $this->error( '修改头像失败！' );
                    exit;
                }

                $avatarImgURL = 'uploads/'.$avatarImgURL;
            }

            if ( empty( request()->file( 'cover' ) ) ) {
                $coverImgURL = isset( $params[ 'cover' ] ) ? $params[ 'cover' ] : $userInfo[ 'cover' ];
            } else {
                // 背景图片上传
                $coverImgURL = upload( 'cover' );

                if ( $coverImgURL === false ) {
                    $this->error( '修改背景失败！' );
                    exit;
                }

                $coverImgURL = 'uploads/'.$coverImgURL;
            }

            // 组装全部信息
            $data = [
                'id' => $params[ 'id' ], // 提交表单中没有id
                'email' => $params[ 'email' ], // 提交表单 email 不可以修改
                'sex' => $params[ 'sex' ],
                'nickname' => $params[ 'nickname' ],
                'province' => $params[ 'province' ],
                'city' => $params[ 'city' ],
                'district' => $params[ 'district' ],
                'point' => $params[ 'point' ],
                'vip' => $params[ 'vip' ],
                'auth' => $params[ 'auth' ],
                'content' => $params[ 'content' ],
                'avatar' => $avatarImgURL,
                'cover' => $coverImgURL,
            ];

            // 修改数据库
            $resultImg = $this->UserModel->isUpdate()->save( $data );

            if ( $resultImg === false ) {

                // 如果更新失败将上传的图片删除
                @is_file( $data[ 'avatar' ] ) && @unlink( $data[ 'avatar' ] );

                $this->error( $this->UserModel->getError() );
                exit;
            } else {
                // 修改成功后，删除原来的图片
                $avatar = ltrim( $userInfo[ 'avatar' ], '/' );
                @is_file( $avatar ) && @unlink( $avatar );

                $this->success( '修改信息成功！', url( 'admin/user/index' ) );
                exit;
            }
            var_dump( $data );

            exit;
        }

        return $this->fetch();
    }

    // 市

    public function area() {
        if ( $this->request->isPost() ) {
            $code = $this->request->param( 'code' );

            $city = $this->RegionModel->where( [ 'parentid' => $code ] )->select();

            //返回json数据
            return json( $city );
        }
    }

    // 区

    public function areadistrict() {
        if ( $this->request->isPost() ) {
            $code = $this->request->param( 'code' );

            $district = $this->RegionModel->where( [ 'parentid' => $code ] )->select();

            //返回json数据
            return json( $district );
        }
    }

    // 修改密码

    public function revpwd() {
        // 获取url传来的数据
        $userId = $this->request->param( 'id', 0 );

        // 根据id获取配置信息
        $userInfo = $this->UserModel->find( $userId );

        $this->assign( [
            'userId' => $userId,
        ] );

        if ( $this->request->isPost() ) {
            // 获取输入的值
            $nowpass = $this->request->param( 'nowpass', '' );
            $pass = $this->request->param( 'pass', '' );
            $repass = $this->request->param( 'repass', '' );

            // 密码盐
            $salt = $userInfo[ 'salt' ];

            // 加密当前密码
            $nowpass = md5( $nowpass.$salt );

            // 判断输入的密码是否与数据库相同
            if ( $nowpass != $userInfo[ 'password' ] ) {
                $this->error( '你输入的密码有误！' );
                exit;
            }

            // 给新密码加密
            $passs = md5( $pass.$salt );

            // 判断旧密码是否与新密码相同
            if ( $nowpass == $passs ) {
                $this->error( '你输入的新密码与原先的密码相同！' );
                exit;
            }

            // 重新生成密码盐
            $salts = randstr( 10 );

            // 新密码加密
            $pass = md5( $pass.$salts );

            // 组装数据
            $data = [
                'id' => $userInfo[ 'id' ],
                'password' => $pass,
                'salt' => $salts
            ];

            // 修改数据库数据
            $resultPassword = $this->UserModel->isUpdate()->save( $data );

            // 判断返回结果
            if ( $resultPassword == false ) {
                $this->error( $this->UserModel->getError() );
                exit;
            } else {
                $this->success( '密码修改成功！', url( 'admin/user/index' ) );
                exit;
            }
        }

        return $this->fetch();
    }

    // 检查输入框是否输入正确

    public function check() {
        $request = [
            'result' => false,
            'msg' => '',
        ];

        // 获取当前登录用户信息
        $userId = $this->request->param( 'userid' );

        // 获取用户其他信息
        $UserInfo = $this->UserModel->where( [ 'id' => $userId ] )->find();

        if ( !$UserInfo ) {
            $this->error( $this->UserModel->getError() );
            exit;
        }

        if ( $this->request->isPost() ) {

            // 获取传来的的信息
            $params = $this->request->param();

            // 昵称操作
            if ( !empty( $params[ 'nickname' ] ) ) {
                // 获取输入的昵称
                $nickname = $params[ 'nickname' ];

                // 查询数据库是否有相同昵称的用户
                $res = $this->UserModel->where( [ 'nickname' => $nickname ] )->find();

                // 查询结果操作
                if ( $res == false ) {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '用户名不存在，可以修改！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else if ( $UserInfo[ 'nickname' ] == $nickname ) {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else {
                    $request[ 'result' ] = false;
                    $request[ 'msg' ] = '用户名已存在，不可以修改！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                }
            }

            // 昵称操作
            if ( !empty( $params[ 'email' ] ) ) {
                // 获取输入的昵称
                $email = $params[ 'email' ];

                // 查询数据库是否有相同昵称的用户
                $res = $this->UserModel->where( [ 'email' => $email ] )->find();

                // 查询结果操作
                if ( $res == false ) {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '邮箱不存在，可以修改！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else if ( $UserInfo[ 'email' ] == $email ) {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else {
                    $request[ 'result' ] = false;
                    $request[ 'msg' ] = '邮箱已存在，不可以修改！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                }
            }

            // 旧密码操作
            if ( !empty( $params[ 'oldpass' ] ) ) {
                //获取输入的密码
                $oldpass = $params[ 'oldpass' ];

                // 密码加密
                $oldpass = md5( $oldpass.$UserInfo[ 'salt' ] );

                // 判断并操作
                if ( $oldpass == $UserInfo[ 'password' ] ) {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '密码正确！继续操作！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else {
                    $request[ 'result' ] = false;
                    $request[ 'msg' ] = '密码错误！请重新输入！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                }
            }

            // 新密码检查
            if ( !empty( $params[ 'newpass' ] ) ) {
                //获取输入的密码
                $newpass = $params[ 'newpass' ];

                // 密码加密
                $newpass = md5( $newpass.$UserInfo[ 'salt' ] );

                // 判断并操作
                if ( $newpass == $UserInfo[ 'password' ] ) {
                    $request[ 'result' ] = false;
                    $request[ 'msg' ] = '密码重复！请重新输入！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                } else {
                    $request[ 'result' ] = true;
                    $request[ 'msg' ] = '密码不重复！继续操作！';
                    echo json_encode( $request, JSON_UNESCAPED_UNICODE );
                    exit;
                }
            }

        }

    }

    // 回收站

    public function recycle() {
        // 获取开始时间
        $start = $this->request->param( 'start', '' );

        // 获取结束时间
        $end = $this->request->param( 'end', '' );

        // 获取关键字
        $keywords = $this->request->param( 'keywords', '' );

        // 条件集合
        $where = [];

        if ( $start ) {
            // 加入条件 大于开始时间
            $where[ 'createtime' ] = [ '> time', $start ];
        }

        if ( $end ) {
            // 加入条件 小于或等于结束时间
            $where[ 'createtime' ] = [ '<= time', $end ];
        }

        // 若两个都存在就将两个条件拼接
        if ( $start && $end ) {
            $where[ 'createtime' ] = [ 'between time', [ $start, $end ] ];
        }

        if ( $keywords ) {
            // 加入条件 关键字
            $where[ 'nickname' ] = [ 'like', "%$keywords%" ];
        }

        // 全部用户的数量
        $userAll = $this->UserModel->onlyTrashed()->select();

        $userCount = count( $userAll );

        // 获取全部用户
        $userList = $this->UserModel->onlyTrashed()->where( $where )->order( 'id', 'desc' )->paginate( 10, false, [ 'query' => Request::instance()->param() ] );

        // 获取分页显示
        $userListstr = $userList->render();

        $this->assign( [
            'userList' => $userList,
            'userListstr' => $userListstr,
            'userCount' => $userCount,
            'keywords' => $keywords,
            'start' => $start,
            'end' => $end,
        ] );
        return $this->fetch();
    }

    // 取消软删除 恢复正常

    public function recovery() {
        if ( $this->request->isPost() ) {
            // 提示信息
            $success = [
                'result' => false,
                'msg' => '',
            ];

            $ids = $this->request->param( 'ids', 0 );

            $where = 'id in('.$ids.')';

            $data = [
                'deletetime' => null,
            ];

            // 软删除
            $result = $this->UserModel->onlyTrashed()->where( $where )->update( [ 'deletetime' => NULL ] );

            if ( $result === FALSE ) {
                $success[ 'result' ] = false;
                $success[ 'msg' ] = $this->UserModel->getError();
            } else {
                $success[ 'result' ] = true;
                $success[ 'msg' ] = '恢复用户成功';
            }

            return json( $success );
        }

    }

    // 真正删除

    public function cut() {
        if ( $this->request->isPost() ) {
            // 提示信息
            $success = [
                'result' => false,
                'msg' => '',
            ];

            $ids = $this->request->param( 'ids', 0 );

            $where = 'id in('.$ids.')';

            // 软删除
            $result = $this->UserModel->onlyTrashed()->where( $where )->delete();

            if ( $result === FALSE ) {
                $success[ 'result' ] = false;
                $success[ 'msg' ] = $this->UserModel->getError();
            } else {
                $success[ 'result' ] = true;
                $success[ 'msg' ] = '删除用户成功';
            }

            return json( $success );
        }
        return '456';
    }

}
?>